<template>
  <a-card :style="{ boxShadow: 'none' }" :bordered="false" :bodyStyle="{ padding: '0' }">
    <a-table @change="pageChange" table-layout="fixed" sticky :row-selection="{
      selectedRowKeys: memoTable.keys,
      onChange: (k: any[]) => (memoTable.keys = k),
    }" bordered :loading="memoTable.loading" :pagination="false" :customRow="customRow"
      :rowKey="memoTable.rowKey" :columns="formatColumns(memoColumns)" :data-source="memoTable.data">
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'operation'">
          <a-dropdown-button trigger="click" @click="memoEdit(record.memoId)"
            @open-change="openChange(record as AxMemo)">
            <EditOutlined />
            <template #overlay>
              <a-menu :items="memoTable.contextmenu"></a-menu>
            </template>
          </a-dropdown-button>
        </template>
      </template>
    </a-table>
  </a-card>
</template>

<script setup lang="ts">
import type { AxMemo } from '@/api/modules/ax/memo/types';
import { formatColumns } from '@/utils/table/table';
import { useArrayFilter } from '@vueuse/core';
import type { TablePaginationConfig } from 'ant-design-vue';
import type { FilterValue, SorterResult } from 'ant-design-vue/es/table/interface';
import { memoColumns } from '../../data/column';
import { memoEdit, memoList } from '../../data/curd';
import { displayMemoMenu } from '../../data/curd';
import { memoFormConfig } from '../../data/form';
import { memoTable } from '../../data/table';
import { useCloned } from '@vueuse/core';

const openChange = (record: AxMemo) => {
  memoFormConfig.value.form = useCloned(record).cloned.value;
};

/* 行事件 */
const customRow = (record: AxMemo) => {
  return {
    onClick() {
      const id = (record as any)[memoTable.value.rowKey]
      memoFormConfig.value.form = record;
      if (!memoTable.value.keys.includes(id)) {
        memoTable.value.keys.push(id);
      } else {
        memoTable.value.keys = useArrayFilter(memoTable.value.keys, e => e !== id).value;
      }
      memoTable.value.keys = [record.memoId];
    },
    onDblclick() {
      memoEdit(record.memoId);
    },
    onContextmenu() {
      displayMemoMenu(record);
    },
  };
};

/* 分页事件触发 */
const pageChange = (
  pagination: TablePaginationConfig,
  filters: Record<string, FilterValue>,
  sorter: SorterResult<AxMemo> | SorterResult<AxMemo>[],
) => {
  if (pagination.current && pagination.pageSize) {
    memoTable.value.query.pageNum = pagination.current;
    memoTable.value.query.pageSize = pagination.pageSize;
  }
  if (!(sorter instanceof Array)) {
    memoTable.value.query.isAsc = sorter.order === 'ascend' ? 'asc' : 'desc';
  }
  memoList();
};
</script>

<style lang="scss" scoped></style>
